package com.laf.sinaweibo.logic;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.laf.sinaweibo.bean.Task;
import com.laf.sinaweibo.ui.IWeiboActivity;

public class MainService extends Service implements Runnable {
	
	private static Queue<Task> tasks = new LinkedList<Task>();
	private boolean isRun;
	private	static ArrayList<Activity> appActivities = new ArrayList<Activity>();  
	
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case Task.WEIBO_LOGIN:
				IWeiboActivity activity = (IWeiboActivity) getActivityByName("LoginActivity");
				
				if (activity != null) {
					activity.refresh(msg.obj);
				}
				break;

			default:
				break;
			}
		}
	};
			
	@Override
	public void onCreate() {
		isRun = true;
		new Thread(this).start();
		
		super.onCreate();
		Log.i("laf",  "onCreate()");
	}

	@Override
	public void run() {
		
		while(isRun) {
			Task task = null;
			
			if (!tasks.isEmpty()) {
				task = tasks.poll();
				
				if (task != null) {
					doTask(task);
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.i("laf",  "onBind()");
		return null;
	}

	public static void newTask(Task task) {
		if (task != null) {
			tasks.add(task);
		}
	}
	
	private void doTask(Task task) {
		Message msg = handler.obtainMessage();
		msg.what = task.getTaskId();
		
		switch (task.getTaskId()) {
		case Task.WEIBO_LOGIN:
			Log.i("laf",  "dotask>>>>weibo_login");

			msg.obj = "login succeed";
		
			break;

		default:
			break;
		}
		
		handler.sendMessage(msg);
	}
	
	public static void addActivity(Activity activity) {
		if (activity != null) {
			appActivities.add(activity);
		}
		return;
	}
	
	private Activity getActivityByName(String name) {
		
		if (!appActivities.isEmpty()) {
			
			for (Activity activity : appActivities) {
				String classname = activity.getClass().getName();
				Log.i("laf", classname);
				if (classname.indexOf(name) != -1) {
					return activity;
				}
			}
		}
		
		return null;
	} 
}
